package dk.pervasivepositioning.project2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.location.Location;
import android.util.Log;

public class HTTPSender {
	final URL url;

	public HTTPSender(String uRL) throws IOException {
		url = new URL("http://daimi.au.dk/~kongsted/GPSPlotter.php");
	}

	public void sendData(Location location, String strategy) throws IOException {


		URL url = new URL("http://daimi.au.dk/~kongsted/GPSPlotter.php");

		HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();

		urlcon.setRequestMethod("POST");
		urlcon.setDoOutput(true);
		OutputStreamWriter writer = new OutputStreamWriter(
				urlcon.getOutputStream());

		String longitude = String.valueOf(location.getLongitude());
		String latitude = String.valueOf(location.getLatitude());
		String altitude = String.valueOf(location.getAltitude());

		String data = URLEncoder.encode("longitude", "UTF-8") + "="
				+ URLEncoder.encode(longitude, "UTF-8");
		data += "&" + URLEncoder.encode("latitude", "UTF-8") + "="
				+ URLEncoder.encode(latitude, "UTF-8");
		data += "&" + URLEncoder.encode("altitude", "UTF-8") + "="
				+ URLEncoder.encode(altitude, "UTF-8");
		data += "&"
				+ URLEncoder.encode("timestamp", "UTF-8")
				+ "="
				+ URLEncoder
						.encode(String.valueOf(location.getTime()), "UTF-8");
		data += "&" + URLEncoder.encode("type", "UTF-8") + "="
				+ URLEncoder.encode(strategy, "UTF-8");
		writer.write(data);
		writer.flush();

		// Get the response
		BufferedReader rd = new BufferedReader(new InputStreamReader(
				urlcon.getInputStream()));
		String line;
		while ((line = rd.readLine()) != null) {
			Log.d("response", line);
		}
		writer.close();
		rd.close();

	}

}
